﻿using System;
using MaxStoreErp.Core.Attributes;
using MaxStoreErp.Core.BaseClasses;
using MaxStoreErp.Core.Commands;
using MaxStoreErp.Core.Events;
using MaxStoreErp.Core.Extensions;
using MaxStoreErp.Core.Interfaces;
using MaxStoreShop.Domain.Directories;
using MaxStoreShop.Logic.ServicesContracts.Directories;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Unity;

namespace MaxStoreShop.CoreModule.Login
{
    [HistoryNotRemembered]
    public class LoginPresenter : PresenterBase<LoginView, LoginViewModel>, IUserLogin
    {
        [Dependency]
        public IUserService UserService { get; set; }
        IDocumentManager _documentManager;

        public IView GetLoginView(IDocumentManager documentManager)
        {
            _documentManager = documentManager;
            LoadDataAsync();
            return View;
        }

        protected override void OnViewModelSet()
        {
            base.OnViewModelSet();
            ViewModel.EnterCommand = new RelayCommand(LoginUser, CanLoginUser);
            ViewModel.OnEnterPassword = () => ViewModel.IsErrorOccured = false;
        }

        void LoginUser()
        {
            try
            {
                UserService.AuthorizeUser((StoreUser) ViewModel.SelectedUser, ViewModel.Password);
                Container.Resolve<IEventAggregator>().GetEvent<ChangedUserEvent>().Publish(ViewModel.SelectedUser);
                _documentManager.NavigateToMenu();
            }
            catch (Exception exception)
            {
                ViewModel.Password = string.Empty;
                ViewModel.ErrorText = exception.Message;
                ViewModel.IsErrorOccured = true;
            }
        }

        bool CanLoginUser()
        {
            return ViewModel.SelectedUser != null && !string.IsNullOrWhiteSpace(ViewModel.Password);
        }

        protected override void OnDataLoading()
        {
            base.OnDataLoading();
            ViewModel.Users = UserService.GetUsers().ToObservableCollection();
            if (ViewModel.Users.Count == 0)
            {
                UserService.SaveUser(new StoreUser {FirstName = "Админ", LastName = "Админов", SecretCode = "0"});
                ViewModel.Users = UserService.GetUsers().ToObservableCollection();
            }
        }
    }
}
